home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 3805 < prev    next >
Encoding:
Text File  |  1996-08-06  |  1.7 KB  |  77 lines

  1. Path: news.compuserve.com!newsmaster
  2. From: <75151.03563@compuserve.com>
  3. Newsgroups: comp.lang.c++
  4. Subject: RE: Copt constructing an already default ....
  5. Date: 26 Jan 1996 02:15:23 GMT
  6. Organization: CompuServe Incorporated
  7. Message-ID: <4e9dfr$spc@dub-news-svc-6.compuserve.com>
  8. NNTP-Posting-Host: dd35-159.compuserve.com
  9. Content-Type: text/plain
  10. Content-length: 1412
  11. X-Newsreader: AIR Mosaic (16-bit) version 3.10.08.25
  12.  
  13.  
  14. > I've go an object which has already been constructed via its default
  15. > constructor which just sets all pointers to NULL.  What's the best
  16. > way to deep-copy into it ??
  17.  
  18. How about:
  19.  
  20. Class A{
  21. public:
  22.   A();
  23.   A( const A & a )                      { deepCopy( a );    }
  24.  
  25.   A & operator= (const A & a )     { deepCopy( a );  return *this; }
  26.  
  27. protected:
  28.   void deepCopy( const A & );
  29.  
  30. private:
  31.   char * m_pData;
  32.   int      m_nDataSize;
  33. };
  34.  
  35. void A::deepCopy( const A & a )
  36. {
  37.   // perform deep copy here
  38.  
  39.   // avoid self-assingment...
  40.   if ( a.m_pData == m_pData )
  41.     return;  
  42.  
  43.   char * tmp= new char[ a.m_nDataSize ];
  44.   if (tmp == NULL)
  45.     return;
  46.  
  47.   m_pData= tmp;
  48.   m_nDataSize= a.m_nDataSize;
  49.  
  50.   memmove( m_pData, a.m_pData, m_nDataSize );
  51. }
  52.  
  53.  
  54. The way you implemented a deep-copy assignment operator :
  55. >>
  56. >> A & A::operator=( const A & other )
  57. >> {
  58. >>    A empty;
  59. >>    A tmp( other );
  60. >>    memcpy( this, &tmp, sizeof( A ) );
  61. >>    memcpy( &tmp, &empty, sizeof( A ) );
  62. >>    return *this;
  63. >>  }
  64. >>
  65.  
  66. jumps through unnecessary hoops, and is dangerous.  It is not a good
  67. idea to memcpy() to an object.  If the object has no virtual functions
  68. you will usually be OK, but if the class does have virtual functions, you
  69. will most likely over-write the virtual function table pointer and 
  70. completely hose yourself.
  71.  
  72. Hope this Helps,
  73.  
  74. Tom Keane
  75. 75151,03563
  76.  
  77.